var portaluserno = getCookie('portaluserno')
var configInfo = InitialParameter("/Config.json");
var modelApi = getBaseplatformPort()
var dashboardData = []
$(document).ready(function () {
    if (!portaluserno) {
        location.href = "/"
    } else {
        getData()
        situationGauge()
        funCp()
        // run() 
    }
})
// 仪表盘渲染
function situationGauge() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('monitoring'));
    // 指定图表的配置项和数据
    var option = {
        // backgroundColor: '#1b1b1b',
        tooltip: {
            formatter: '{b}{c}'
        },
        toolbox: {
            show: true,
            feature: {
                mark: {
                    show: true
                },
                restore: {
                    show: true
                },
                saveAsImage: {
                    show: true
                }
            }
        },
        series: [{
                name: '运行时间(天)',
                type: 'gauge',
                min: 0,
                max: 220,
                splitNumber: 11,
                radius: '100%',
                axisLine: { // 坐标轴线
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: [
                            [0.09, 'lime'],
                            [0.82, '#1e90ff'],
                            [1, '#ff4500']
                        ],
                        width: 3,
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                axisLabel: { // 坐标轴小标记
                    fontWeight: 'bolder',
                    color: '#fff',
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 10
                },
                axisTick: { // 坐标轴小标记
                    length: 15, // 属性length控制线长
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: 'auto',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                splitLine: { // 分隔线
                    length: 25, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                        width: 3,
                        color: '#fff',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                pointer: { // 分隔线
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 5
                },
                // detail: {
                //     backgroundColor: 'rgba(30,144,255,0.8)',
                //     borderWidth: 1,
                //     borderColor: '#fff',
                //     shadowColor: '#fff', //默认透明
                //     shadowBlur: 5,
                //     offsetCenter: [0, '50%'],       // x, y，单位px
                //     textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                //         fontWeight: 'bolder',
                //         color: '#fff'
                //     }
                // }, 
                title: { //设置仪表盘中间显示文字样式
                    textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontWeight: 'bold',
                        fontSize: 10,
                        fontStyle: 'italic',
                        color: "black"
                    }
                },
                data: [{
                    value: 40,
                    name: '运行时间(天)'
                }]
            },
            {
                name: 'CPU核数',
                type: 'gauge',
                center: ['25%', '55%'], // 默认全局居中
                radius: '100%',
                min: 0,
                max: 7,
                endAngle: 45,
                splitNumber: 7,
                axisLine: { // 坐标轴线
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: [
                            [0.29, 'lime'],
                            [0.86, '#1e90ff'],
                            [1, '#ff4500']
                        ],
                        width: 2,
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                axisLabel: { // 坐标轴小标记
                    fontWeight: 'bolder',
                    color: '#fff',
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 10
                },
                axisTick: { // 坐标轴小标记
                    length: 12, // 属性length控制线长
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: 'auto',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                splitLine: { // 分隔线
                    length: 20, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                        width: 3,
                        color: '#fff',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                pointer: {
                    width: 5,
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 5
                },
                title: {
                    offsetCenter: [0, '-30%'], // x, y，单位px
                    textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontWeight: 'bolder',
                        fontStyle: 'italic',
                        color: '#fff',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                title: { //设置仪表盘中间显示文字样式
                    textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontSize: 10,
                        fontStyle: 'italic',
                        color: "black"
                    }
                },
                data: [{
                    value: 1.5,
                    name: 'CPU核数(个)'
                }]
            },
            {
                name: '内存容量',
                type: 'gauge',
                center: ['75%', '50%'], // 默认全局居中
                radius: '100%',
                min: 0,
                max: 2,
                startAngle: 135,
                endAngle: 45,
                splitNumber: 2,
                axisLine: { // 坐标轴线
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: [
                            [0.2, 'lime'],
                            [0.8, '#1e90ff'],
                            [1, '#ff4500']
                        ],
                        width: 2,
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                axisTick: { // 坐标轴小标记
                    length: 12, // 属性length控制线长
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: 'auto',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                axisLabel: {
                    fontWeight: 'bolder',
                    color: '#fff',
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 10,
                    formatter: function (v) {
                        switch (v + '') {
                            case '0':
                                return 'E';
                            case '1':
                                return '内存容量';
                            case '2':
                                return 'F';
                        }
                    }
                },
                splitLine: { // 分隔线
                    length: 15, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                        width: 3,
                        color: '#fff',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                pointer: {
                    width: 2,
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 5
                },
                title: {
                    show: false
                },
                detail: {
                    show: false
                },
                title: { //设置仪表盘中间显示文字样式
                    textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontSize: 10,
                        fontStyle: 'italic',
                        color: "rgb(99, 156, 198)"
                    }
                },
                data: [{
                    value: 0.5,
                    name: '内存容量(G)'
                }]
            },
            {
                name: '硬盘容量',
                type: 'gauge',
                center: ['75%', '50%'], // 默认全局居中
                radius: '100%',
                min: 0,
                max: 2,
                startAngle: 315,
                endAngle: 225,
                splitNumber: 2,
                axisLine: { // 坐标轴线
                    lineStyle: { // 属性lineStyle控制线条样式
                        color: [
                            [0.2, 'lime'],
                            [0.8, '#1e90ff'],
                            [1, '#ff4500']
                        ],
                        width: 2,
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                axisTick: { // 坐标轴小标记
                    show: false
                },
                axisLabel: {
                    fontWeight: 'bolder',
                    color: '#fff',
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 10,
                    formatter: function (v) {
                        switch (v + '') {
                            case '0':
                                return 'H';
                            case '1':
                                return '磁盘容量';
                            case '2':
                                return 'C';
                        }
                    }
                },
                splitLine: { // 分隔线
                    length: 15, // 属性length控制线长
                    lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                        width: 3,
                        color: '#fff',
                        shadowColor: '#fff', //默认透明
                        shadowBlur: 10
                    }
                },
                pointer: {
                    width: 2,
                    shadowColor: '#fff', //默认透明
                    shadowBlur: 5
                },
                title: {
                    show: false
                },
                detail: {
                    show: false
                },
                title: { //设置仪表盘中间显示文字样式
                    textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                        fontSize: 10,
                        fontStyle: 'italic',
                        color: "rgb(99, 156, 198)"
                    }
                },
                data: [{
                    value: 0.5,
                    name: '硬盘容量(G)'
                }]
            }
        ]
    };
    let memoryAllSizeNew = dashboardData.memoryAllSize
    let str = memoryAllSizeNew.lastIndexOf('G')
    let newStr = memoryAllSizeNew.substring(0, str)
    let driverZ = dashboardData.driver
    let totalCapacityRl = 0
    driverZ.map(item => {
        totalCapacityRl += item.driveUses
    })
    option.series[0].data[0].value = dashboardData.runTimes
    option.series[1].data[0].value = dashboardData.block
    option.series[2].data[0].value = newStr
    option.series[3].data[0].value = totalCapacityRl
    myChart.setOption(option);
    window.onresize = function () {
        myChart.resize();
    } 
    var processorChart = echarts.init(document.getElementById('processorTemperatureGauge'));
    let processorChartOption = {
        title: {
            text: '处理器温度'
        },
        tooltip:{
            formatter:function (data) {
                return `处理器温度：${data.value}℃`
            }
        },
        series: [{
            type: 'gauge',
            axisLine: {
                lineStyle: {
                    width: 30,
                    color: [
                        [0.3, '#67e0e3'],
                        [0.7, '#37a2da'],
                        [1, '#fd666d']
                    ]
                }
            },
            pointer: {
                itemStyle: {
                    color: 'auto'
                }
            },
            axisTick: {
                distance: 5,
                length: 6,
                lineStyle: {
                    color: '#fff',
                    width: 2
                }
            },
            
            detail: {
                valueAnimation: true,
                formatter: '{value} ℃',
                color: 'auto'
            },
            data: [{
                value: dashboardData.cpuTemperature
            }]
        }]
    };
    processorChart.setOption(processorChartOption);
    window.onresize = function () {
        processorChart.resize();
    } 
}
// 渲染磁盘空间
function funCp() {
    let dataDriver = dashboardData.driver
    // console.log(dashboardData);
    // if (dataDriver.length > 4) {
    //     $('#kongjianCPChild').css({
    //         width: $('#kongjianCP').outerWidth() / dashboardData.driver.length + '%'
    //     })
    //     $('#kongjianCPFather').css({
    //         overflowX: 'scroll'
    //     })
    // } else {
    //     $('#kongjianCPChild').css({
    //         width: '25%',
    //     })
    // }
    // 渲染表格  
    let htmlCp = ''
    dataDriver.map((item, index) => {
        htmlCp += `
            <div style="width:25%;border-right: 1px rgb(226, 226, 226) solid;" id="kongjianCPChild">
                <div style="height: 10%;line-height: 30px;text-align: center;border-bottom: 1px rgb(226, 226, 226) solid;">${item.name}</div>
                <div style="width:100%;height:calc(60% + 2px);border-bottom: 1px rgb(226, 226, 226) solid;display:flex;justify-content: center">
                    <canvas id="cavName${index}"></canvas>
                </div>
                <div style="height:15%;display:flex;justify-content: center;align-items: center;width: 100%;border-bottom: 1px rgb(226, 226, 226) solid;">
                    可用空间:${item.driveUses - item.driveUsed}G
                </div>
                <div style="height:15%;display:flex;justify-content: center;align-items: center;width: 100%;border-bottom: 1px rgb(226, 226, 226) solid;">
                    总空间:${item.driveUses}G
                </div>
            </div>
        `
        setDisk('cavName' + index, item.driveUsedLv)
        return htmlCp
    })
    $('#kongjianCPFather').html(htmlCp)

}
// 磁盘空间的canves
function setDisk(dom, num) {
    $(document).ready(function () {
        var canvas = document.getElementById(dom);
        var ctx = canvas.getContext('2d');
        //range控件信息
        var rangeValue;
        var nowRange = 0; //用于做一个临时的range
        //画布属性
        var mW = canvas.width = 135;
        var mH = canvas.height = 135;
        var lineWidth = 2;
        //圆属性
        var r = mH / 2; //圆心
        var cR = r - 16 * lineWidth; //圆半径
        //Sin 曲线属性
        var sX = 0;
        var sY = mH / 2;
        var axisLength = mW; //轴长
        var waveWidth = 0.015; //波浪宽度,数越小越宽 
        var waveHeight = 6; //波浪高度,数越大越高
        var speed = 0.09; //波浪速度，数越大速度越快
        var xOffset = 0; //波浪x偏移量 
        ctx.lineWidth = lineWidth;
        //画圈函数
        var IsdrawCircled = false;
        var drawCircle = function () {
            ctx.beginPath();
            ctx.strokeStyle = '#1080d0';
            ctx.arc(r, r, cR + 5, 0, 2 * Math.PI);
            ctx.stroke();
            ctx.beginPath();
            ctx.arc(r, r, cR, 0, 2 * Math.PI);
            ctx.clip();
        }
        //画sin 曲线函数
        var drawSin = function (xOffset) {
            ctx.save();
            var points = []; //用于存放绘制Sin曲线的点
            ctx.beginPath();
            //在整个轴长上取点
            for (var x = sX; x < sX + axisLength; x += 20 / axisLength) {
                //此处坐标(x,y)的取点，依靠公式 “振幅高*sin(x*振幅宽 + 振幅偏移量)”
                var y = -Math.sin((sX + x) * waveWidth + xOffset);
                var dY = mH * (1 - nowRange / 100);
                points.push([x, dY + y * waveHeight]);
                ctx.lineTo(x, dY + y * waveHeight);
            }
            //封闭路径
            ctx.lineTo(axisLength, mH);
            ctx.lineTo(sX, mH);
            ctx.lineTo(points[0][0], points[0][1]);
            ctx.fillStyle = '#1c86d1';
            ctx.fill();
            ctx.restore();
        };
        //写百分比文本函数
        var drawText = function () {
            ctx.save();
            var size = 0.4 * cR;
            ctx.font = size + 'px Microsoft Yahei';
            ctx.textAlign = 'center';
            ctx.fillStyle = "rgba(06, 85, 128, 0.8)";
            ctx.fillText(~~nowRange + '%', r, r + size / 2);
            ctx.restore();
        };
        var render = function () {
            ctx.clearRect(0, 0, mW, mH);
            rangeValue = num;
            if (IsdrawCircled == false) {
                drawCircle();
            }
            if (nowRange <= rangeValue) {
                var tmp = 1;
                nowRange += tmp;
            }
            if (nowRange > rangeValue) {
                var tmp = 1;
                nowRange -= tmp;
            }
            drawSin(xOffset);
            drawText();
            xOffset += speed;
            requestAnimationFrame(render);
        }
        render();
    })

}
// 获取表盘数据
function getData() {
    var results = sendAjax(modelApi + "hardwareInfo/getCpuInfo", "POST");
    if (results.code == 200) {
        dashboardData = results.data
        let totalCapacity = 0
        let beenUsed = 0
        dashboardData.driver.map(item => {
            totalCapacity += item.driveUses
            beenUsed += item.driveUsed
        })
        let comTotal = Math.ceil(beenUsed / totalCapacity * 100)
        var progressBar1 = new Pie('progressBar', Number(dashboardData.cpuUsedLV * 100));
        var progressBar2 = new Pie('progressBarCpu', Number(dashboardData.memoryUsedLv * 100));
        var progressBar3 = new Pie('progressBarCp', comTotal);
        var progressBar4 = new Pie('progressBarZcp', 70);
        $('#textWindow').html(dashboardData.vendorName)
        $('#windowIp').html(dashboardData.ip)
        $('#cpuName').html(dashboardData.cpuName)
    }
}
// 进图条js 
var timer = null
var timerNum = 30
clearTimeout(timer)
timer = setTimeout(() => {
    timerNum = Math.round(Math.random() * (85 - 45) + 45)
}, 500);

// function run(tol) {
//     console.log();
//     var bar = document.getElementById("bar");
//     var total = document.getElementById("total");
//     bar.style.width = parseInt(bar.style.width) + 1 + "%";
//     let str = bar.style.width

//     let strIndex = str.lastIndexOf('%')
//     let newStr = str.substring(0, strIndex)
//     total.innerHTML = newStr + '℃';
//     if (bar.style.width == timerNum + "%") {
//         if (str < '80%') {
//             $('#total2').html('正常')
//         } else {
//             // 45 - 85 
//             $('#total2').html('超标')
//             $('#total2').css({
//                 color: "red"
//             })
//         }
//         window.clearTimeout(timeout);
//         return;
//     }
//     var timeout = window.setTimeout("run()", 10);
// }

// 进度条方法
function Pie(id, num) {
    this.box = document.getElementById(id); //获取节点
    this.box.className = 'wrap';

    //创建节点circle
    this.circle = document.createElement("div");
    this.circle.className = "circle";
    this.box.appendChild(this.circle);

    //创建circle的子节点left
    this.left = document.createElement("div");
    if (id == 'progressBar') {
        this.left.className = "left1";
    } else if (id == 'progressBarCpu') {
        this.left.className = "left2";
    } else if (id == 'progressBarCp') {
        this.left.className = "left3";
    } else if (id == 'progressBarZcp') {
        this.left.className = "left4";
    }
    this.circle.appendChild(this.left);

    //创建circle的子节点right
    this.right = document.createElement("div");
    this.right.className = "right";
    if (id == 'progressBar') {
        this.right.className = "right1";
    } else if (id == 'progressBarCpu') {
        this.right.className = "right2";
    } else if (id == 'progressBarCp') {
        this.right.className = "right3";
    } else if (id == 'progressBarZcp') {
        this.right.className = "right4";
    }
    this.circle.appendChild(this.right);

    //创建节点num
    this.num = document.createElement("div");
    if (id == 'progressBar') {
        this.num.className = "num1";
    } else if (id == 'progressBarCpu') {
        this.num.className = "num2";
    } else if (id == 'progressBarCp') {
        this.num.className = "num3";
    } else if (id == 'progressBarZcp') {
        this.num.className = "num4";
    }
    this.box.appendChild(this.num);
    this.num.innerHTML = '<span id="">' + num + '</span>%';
    // this.num.innerHTML = '<span id="">' + num + '</span>';
    this.jz(num);
}
Pie.prototype.jz = function (num) {
    var i = 0;
    var that = this;
    var int = setInterval(function () {
        that.gx(num / 10 * i);
        i++;
        if (i > 10) {
            clearInterval(int)
        }
    }, 50);
}
Pie.prototype.gx = function (n) {
    if (n <= 50) {
        this.right.style.display = 'none';
        this.circle.style.clip = 'rect(0, 100px, 100px, 50px)';
    } else {
        this.right.style.display = 'block';
        this.circle.style.clip = 'rect(auto, auto, auto, auto)';
    }
    this.left.style.transform = 'rotate(' + n * 360 / 100 + 'deg)';
}
// 进度条方法结束
function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}